﻿using ExcelParser.Writer;
using System;
using System.Reflection;

namespace ExcelParser.CodeGen
{
    public class SimpleField : ExcelField
    {
        public SimpleField(string type, string name, string desc) : base(type, name, desc) { }

        public override void GenCode(CodeWriter writer)
        {
            base.GenCode(writer);
            string fieldName = "m_" + Name.Substring(0, 1).ToLower() + Name.Substring(1);
            writer.WriteLine("private {0} {1};", writer.ConvertType(Type), fieldName);
            writer.WriteLine("public {0} {1}", writer.ConvertType(Type), Name);
            writer.WriteLine("{{");
            writer.Indent++;
            writer.WriteLine("get {{ return {0}; }}", fieldName);
            writer.WriteLine("set {{ {0} = value; }}", fieldName);
            writer.Indent--;
            writer.WriteLine("}}");
        }

        public override void ParseValue(CodeWriter writer, object obj, PropertyInfo propertyInfo, MethodInfo methodInfo, Type fieldType, string value)
        {
            string typeString = writer.ConvertFullType(Type);
            System.Type simpleType = System.Type.GetType(typeString);
            MethodInfo tryParseMethod = simpleType.GetMethod("TryParse", new Type[] { typeof(string), simpleType.MakeByRefType() });
            object v = null;
            if (tryParseMethod != null)
            {
                object[] objs = new object[] { value, null };
                tryParseMethod.Invoke(null, objs);
                v = objs[1];
            }
            else
            {
                v = value;
            }
            if (propertyInfo != null)
            {
                propertyInfo.SetValue(obj, v, null);
            }
            if (methodInfo != null)
            {
                methodInfo.Invoke(obj, new object[] { v });
            }
        }
    }
}